package com.xiaobai.demo.controller;

import com.xiaobai.demo.pojo.Diagnostic;
import com.xiaobai.demo.service.DiagnosticService;
import com.xiaobai.demo.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/diagnostics")
public class DiagnosticController {

    @Autowired
    private DiagnosticService diagnosticService;

    // 查询所有诊断记录
    @GetMapping("/findall")
    public Result findAll() {
        List<Diagnostic> list = diagnosticService.findAll();
        return Result.success(list, "查询成功");
    }

    // 根据 id 查询诊断记录
    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        Diagnostic diagnostic = diagnosticService.findById(id);
        if (diagnostic != null) {
            return Result.success(diagnostic, "查询成功");
        } else {
            return Result.failure(404, "记录不存在");
        }
    }

    // 根据 userId 查询诊断记录
    @GetMapping("/user/{userId}")
    public Result findByUserId(@PathVariable Integer userId) {
        List<Diagnostic> list = diagnosticService.findByUserId(userId);
        return Result.success(list, "查询成功");
    }

    // 新增诊断记录
    @PostMapping
    public Result save(@RequestBody Diagnostic diagnostic) {
        diagnostic.setCreatedAt(new Date());
        diagnostic.setUpdatedAt(new Date());
        int result = diagnosticService.save(diagnostic);
        if (result > 0) {
            return Result.success(result, "添加成功");
        } else {
            return Result.failure(500, "添加失败");
        }
    }

    // 更新诊断记录
    @PutMapping
    public Result update(@RequestBody Diagnostic diagnostic) {
        diagnostic.setUpdatedAt(new Date());
        int result = diagnosticService.update(diagnostic);
        if (result > 0) {
            return Result.success(result, "更新成功");
        } else {
            return Result.failure(500, "更新失败");
        }
    }

    // 删除诊断记录
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        int result = diagnosticService.delete(id);
        if (result > 0) {
            return Result.success(result, "删除成功");
        } else {
            return Result.failure(500, "删除失败");
        }
    }
}